﻿/*----------------------------------------------------------------
// Copyright (C) 2013 上海汽车集团股份有限公司
// 版权所有。
//
// 文件名：UI.js
// 文件功能描述：jqGrid 、 DataPicker  、Highcharts  封装
//              文件依赖： 
//                       jquery-1.8.0.min.js、
//                       Common.js  
//                       jquery.jqGrid.min.js
//                       WdatePicker.js
//
//
// 创建标识：  曹珊 2013/8/16`
//
// 修改标识：
// 修改描述：
//
//----------------------------------------------------------------*/


(function ($) {

    $.fn.grid = function (option) {
        if (isNullOrEmpty($(this).attr('id'))) {
            jqAlert("未指定ID的Grid对象"); return;
        }
        //列名创建
        var defColModel = { width: 100, align: 'center', sortable: true };

        if (!isNullOrEmpty(option.colModel)) {
            if (option.colModel.length != option.colNames.length) {
                jqAlert("colModel与colNames长度不一致"); return;
            }

            for (var i = 0; i < option.colModel.length; i++) {
                if (isNullOrEmpty(option.colModel[i].name)) {
                    jqAlert("未指定name属性的colModel"); return;
                }

                if (isNullOrEmpty(option.colModel[i].index)) option.colModel[i].index = option.colModel[i].name;

                if (isNullOrEmpty(option.colModel[i].width)) option.colModel[i].width = defColModel.width;

                if (isNullOrEmpty(option.colModel[i].align)) option.colModel[i].align = defColModel.align;

                if (option.colModel[i].sortable == undefined) option.colModel[i].sortable = defColModel.sortable;
            }
        } else {
            jqAlert("未指定colModel属性的Grid对象"); return;
        }

        var defaults = {
            ajaxGridOptions: {
                type: "POST",
                cache: false,
                async: true,
                error: function () { jqAlert("意外出错，请刷新页面重试!"); }
            },
            loadui: "block",
            datatype: "local",
            gridview: true,
            viewrecords: true,
            multiselect: true,
            rowNum: 10,
            rowList: [10, 30, 50, 100, 200, 500],
            jsonReader: {
                root: "Content.rows",
                total: "Content.total",
                page: "Content.page",
                records: "Content.records",
                repeatitems: false,
                id: "UID"
            },
            caption: "",
            onRightClickRow: function (rowid, iRow, iCol, e) {
                if (!$.browser.msie) return;
                rMenu = $("#gridRightMenu");
                rMenu.css({ "top": e.clientY + "px", "left": e.clientX + "px", "visibility": "visible" });
                $("body").bind("mousedown", RithtMenuMothDown);
                gridID = $(this).attr("id");
                e.preventDefault();
            },
            colRDModel: { FormID: "", RDModel: [] },
            showPager: true,
            width: GetGridContainerWidth(),
            height: GetGridContainerHeight(),
            loadCompleteOnFaildCallBack: function () { },
            gridResize: null, //设置Grid的大小
            gridScroll: false, //是否显示Grid滚动条
            mtype: "POST" // add by Mayan jq默认使用POST方式提交到服务端
        };

        var options = $.extend(defaults, option);
        var $gridObj = $(this).eq(0);

        var customerLoadComplete = function (data) { ; };
        if (options.loadComplete != undefined && $.type(options.loadComplete) == 'function') {
            customerLoadComplete = options.loadComplete;
        }

        var loadCompleteFn = function (xhr) {
            var currenType = $gridObj.getGridParam('datatype');
            if (currenType == "json") {
                ajaxSuccess(xhr, null, options.loadCompleteOnFaildCallBack);
            }
            customerLoadComplete(xhr);
        };
        //从服务器返回响应时执行
        options.loadComplete = loadCompleteFn;

        //ID字段名
        if (options.idKey != undefined && options.idKey != null) {
            options.jsonReader.id = options.idKey;
        }

        //是否显示滚动条 
        if (!options.gridScroll) {
            options.autoWidth = true;
        } else {
            options.shrinkToFit = false;
            options.autoScroll = true;
        }

        //创建分页区 
        if (options.showPager) {
            var pagerId = $gridObj.attr('id') + "_pager";
            $gridObj.siblings('div.gridpager[id="' + pagerId + '"]').remove();
            $gridObj.parent().append("<div id='" + pagerId + "' class='gridpager'></div>");
            options.pager = "#" + pagerId;
        }

        //Grid数据
        if (!isNullOrEmpty(options.colRDModel.FormID)) {
            var $form = $("#" + options.colRDModel.FormID);
            if ($form.length != 0) {
                var cols = options.colRDModel.RDModel.toString();
                var hidObj = "<input type='hidden' GridID='" + $gridObj.attr('id');
                hidObj += "' class='____HIDGRIDDATA' id='hidGridData' name='hidGridData' value=''";
                hidObj += " RDModel='" + cols + "'/>";
                $form.find('input[type="hidden"][name="hidGridData"]').remove();
                $form.append(hidObj);
            }
            //显示和隐藏列hidden
            var colTemp = [];
            for (var k = 0; k < option.colModel.length; k++) {
                colTemp.push(option.colModel[k].name);
            }
            for (var j = 0; j < options.colRDModel.RDModel.length; j++) {
                var value = options.colRDModel.RDModel[j];
                if (!colTemp.contains(value)) {
                    option.colNames.push(value);
                    var col = { name: value, index: value, hidden: true };
                    option.colModel.push(col);
                }
            }
        }

        var rMenu = null;

        this.init = function () {
            if (options.datatype == "local") {
                this.loadLocalData();
            } else {
                this.loadJsonData();
            }
            //this.reload();
        }

        this.loadLocalData = function () {
            var firstOptions = {};
            firstOptions.datatype = "local";
            firstOptions = $.extend(defaults, firstOptions)
            $gridObj.jqGrid(firstOptions);
        };

        this.loadJsonData = function () {
            $gridObj.jqGrid("setGridParam", {
                datatype: "json",
                url: options.url,
                postData: getPostData('QueryForm')
            });
        };

        this.reload = function () {
            $gridObj.jqGrid().trigger("reloadGrid");
        };

        //右键菜单
        function RithtMenuMothDown(event) {
            if (!(event.target.id == 'gridRightMenu' || $(event.target).parents("#gridRightMenu").length > 0)) {
                rMenu.css({ "visibility": "hidden" });
            }
        };

        //大小重置
        this.gridResize = function () {
            if ($.type(options.gridResize) == "function") {
                options.gridResize.call();
                $(window).resize(function () {
                    options.gridResize.call();
                });
            } else {
                $(window).resize(function () {
                    $gridObj.setGridHeight(GetGridContainerHeight()).setGridWidth(GetGridContainerWidth());
                });
            }
        }

        this.init();

        this.gridResize();

        $(window).resize();
    };

})(jQuery);

var gridID = null;
function RightMenuCopy() {
    if (gridID == null) return;

    var selids = $("#" + gridID).jqGrid('getGridParam', 'selarrrow');
    var rows = [];
    for (var i = 0; i < selids.length; i++) {
        var row = $("#" + gridID).jqGrid('getRowData', selids[i]);
        rows.push(row);
    }

    if (rows.length == 0) {
        jqAlert("请勾选数据！");
        return;
    }

    var result = '';
    for (var i = 0; i < rows.length; i++) {
        for (var item in rows[i]) {
            result += rows[i][item].replace(/<[^>]+>/g, "") + "\t";
        }
        result += "\r\n";
    }

    if (window.clipboardData) {
        if (window.clipboardData.setData("Text", result))
            jqAlert("数据已经复制到剪切板！");
    }
};


/*
my97 datePicker 

1、默认日期格式: yyyy-MM-dd 其他格式请指定 DateFmt；
2、单个日期控件: 必要参数 pickerID：控件id ; 
非必要参数 startDate： 默认起始日期
minDate： 静态限制作用的最小日期
maxDate： 静态限制作用的最大日期 ；

3、两个日期控件: 必要参数 start、 end;
非必要参数 minDate：起始控件最小日期
maxDate：结束控件最大日期

*/
(function ($) {
    $.DataPicker = function (settings) {

        settings = jQuery.extend({
            skin: 'default',
            dateFmt: 'yyyy-MM-dd HH:mm:ss'
        }, settings);

        var pickerSettings = {
            skin: settings.skin,
            dateFmt: settings.dateFmt
        };

        //单个日期控件
        var isSingle = !isNullOrEmpty(settings.pickerID);
        if (isSingle) {

            var picker = $('#' + settings.pickerID);

            if (picker.length == 0) {
                jqAlert("请指定正确的控件ID [pickerID] !");
                return;
            };

            if (!picker.hasClass('Wdate')) picker.addClass('Wdate');

            if (!isNullOrEmpty(settings.startDate)) {
                pickerSettings.startDate = settings.startDate;
            }

            if (!isNullOrEmpty(settings.minDate)) {
                pickerSettings.minDate = settings.minDate;
            }

            if (!isNullOrEmpty(settings.maxDate)) {
                pickerSettings.maxDate = settings.maxDate;
            }
            picker.click(function () {
                WdatePicker(pickerSettings);
            });
            picker.focus(function () {
                WdatePicker(pickerSettings);
            });
        } else {

            //两个日期控件 动态限制
            if (!isNullOrEmpty(settings.start) && !isNullOrEmpty(settings.end)) {

                var startPicker = $('#' + settings.start);

                if (startPicker.length == 0) {
                    jqAlert("请指定正确的控件ID [pickerID] !");
                    return
                };
                var endPicker = $('#' + settings.end);

                if (endPicker.length == 0) {
                    jqAlert("请指定正确的控件ID [pickerID] !");
                    return
                };

                startPicker.focus(function () { });
                endPicker.focus(function () { });

                if (!startPicker.hasClass('Wdate')) startPicker.addClass('Wdate');
                if (!endPicker.hasClass('Wdate')) endPicker.addClass('Wdate');

                var startPickerMaxDate = '#F{$dp.$D(\'' + settings.end + '\')';
                if (!isNullOrEmpty(settings.maxDate)) {
                    startPickerMaxDate += '||\'' + settings.maxDate + '\'';
                }
                startPickerMaxDate += "}";

                var startPickerSettings = jQuery.extend({
                    maxDate: startPickerMaxDate
                }, pickerSettings);

                if (!isNullOrEmpty(settings.minDate)) {
                    startPickerSettings.minDate = settings.minDate;
                }

                var endPickerMinDate = '#F{$dp.$D(\'' + settings.start + '\')}';

                var endPickerSettings = jQuery.extend({
                    minDate: endPickerMinDate
                }, pickerSettings);

                if (!isNullOrEmpty(settings.maxDate)) {
                    endPickerSettings.maxDate = settings.maxDate;
                }

                //修改单击文本框日期面板不弹出的问题
                endPicker.click(function () {
                    WdatePicker(endPickerSettings);
                });

                startPicker.click(function () {
                    WdatePicker(startPickerSettings);
                });

                endPicker.focus(function () {
                    WdatePicker(endPickerSettings);
                });

                startPicker.focus(function () {
                    WdatePicker(startPickerSettings);
                });
            }
        }

        function getPickerArgs(o) {
            var endArgs = '';
            for (var item in endPickerSettings) {
                endArgs += item;
                endArgs += ":\"";
                endArgs += endPickerSettings[item];
                endArgs += "\" ";
                endArgs += ",";
            }
            endArgs = endArgs.substring(0, endArgs.length - 1);

            return endArgs;
        }
    }
})(jQuery);

(function ($) {
    jQuery.hightChart = function (settings) {
        settings = jQuery.extend({
            width: 1200,
            exporting: {
                url: '/HighchartsExport.axd',
                filename: 'MyChart',
                width: 1200
            }
        }, settings);

        settings.exporting.width = settings.width;

        var saicChart = new Highcharts.Chart(settings);

        return saicChart;
    }
})(jQuery);